import Taro, { useLoad, useReachBottom } from '@tarojs/taro'
import { useState } from 'react'
import {
  getAllCategory,
  getHomeProductList,
  getHotGoodList,
} from '@/api/myOrder'
import { ProductList } from '@/components/ProductList'
import Divider from '@/components/Divider'
import Swipers from '@/components/Swipers'
import styles from './index.module.scss'
import CategoryBox from './components/CategoryBox'

interface Product {
  id: number
  name: string
  coverUrl: string
  price: number
  isOver: boolean
  score: number | null // 允许score为null或者数字
}
const pageSize = 5
export default function Home() {
  const [categoryList, setCategoryList] = useState([])
  const [homeProductList, setHomeProductList] = useState([])
  const [hotGoodList, setHotGoodList] = useState<Product[]>([])
  const [page, setPage] = useState(1)

  const fetchGetAllCategory = async () => {
    const res = await getAllCategory()
    setCategoryList(res.data)
  }

  const fetchGetHomeProductList = async () => {
    const res = await getHomeProductList({
      pageSize,
      page,
    })
    if (res.code == 0) {
      setHomeProductList((list) => [...list, ...res.data])
      setPage((pageCur) => pageCur + 1)
    } else if (res.code === 1002) {
      Taro.showToast({
        title: '没有更多数据了,请勿重复下拉',
        icon: 'none',
      })
    } else {
      Taro.showToast({
        title: res.msg,
        icon: 'none',
      })
    }
  }

  const fetchGetHotGoodList = async () => {
    const res = await getHotGoodList()
    console.log(res)

    setHotGoodList(res.data.hotProductList)
  }

  useLoad(() => {
    fetchGetAllCategory()
    fetchGetHomeProductList()
    fetchGetHotGoodList()
  })

  useReachBottom(() => {
    console.log('onReachBottom')
    fetchGetHomeProductList()
  })

  return (
    <>
      <div className={styles.home}>
        <Swipers
          list={hotGoodList.slice(0, 5).map((item) => item.coverUrl)}
          width='678px'
        />
        <CategoryBox list={categoryList}></CategoryBox>
        <ProductList list={homeProductList} />
        <Divider></Divider>
      </div>
    </>
  )
}
